<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use JPush\Client as Jpush;
use Exception;
use DB;

/**
 * Class Curl
 * @package App
 */
class Curl extends Model
{

    //请求的URL
//    const CURL_URI = 'https://wechatlt.jkbanlv.com';
    const CURL_URI = 'http://192.168.1.111:80';
    const CURL_URL = 'https://wechatlt.jkbanlv.com/api';
    //接口
    const CURL_PUSH = '/push/push';//推送消息
    const CURL_ACTLOOK = '/atc/articleById';//查看帖子
    const CURL_ACTPINGLOOK = '/ping/ping';//查看帖子的回复
    const CURL_HUITIE = '/ping/pingAdd';//回帖
    const CURL_ACTSAVE = '/atc/save';//发布文章
    const CURL_ACTIVE = '/ding/add';//活动
    const CURL_ORDERPUSH = '/push/SendToOne';//推送消息

    /**
     * 发送post的curl请求
     * @param $uri
     * @param array $params
     * @param string $type
     * @return mixed
     */
    static function PostCurl($uri, $params = array())
    {
        $url = self::CURL_URI . $uri;
        $params['pcs'] = 3;
        $params = http_build_query($params);
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $params);
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_TIMEOUT, (int)30);
        $output = curl_exec($con);
        curl_close($con);
        return json_decode($output, true);
    }


    /**
     * 发送get的curl请求
     * @param $url
     * @param array $params
     * @return mixed
     */
    static function GetCurl($url, $params = [])
    {
        //拼接URL
        $url = self::CURL_URI . $url;
        $url = $url . '?pcs=3';
        if ($params) {
            foreach ($params as $key => $value) {
                $url .= '&' . $key . '=' . $value;
            }
        }

        $this_header = array(
            "content-type: application/x-www-form-urlencoded; charset=UTF-8"
        );
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this_header);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return json_decode($tmpInfo, true);    //返回json对象
    }

    /**
     * 生成uuid
     * @return string
     */
    static function CreateUuid()
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid = substr($str, 0, 8) . '-';
        $uuid .= substr($str, 8, 4) . '-';
        $uuid .= substr($str, 12, 4) . '-';
        $uuid .= substr($str, 16, 4) . '-';
        $uuid .= substr($str, 20, 12);
        return $uuid;

    }

    /**
     * 极光推送
     * @param $alias
     * @param $content
     * @return array|\Exception|Exception
     */
    static function PushOne($alias, $content)
    {

        try {
            $jpush = new Jpush(env('JPUSH_KEY'), env('JPUSH_SECRET'));
            $jpush = $jpush->push()
                ->setPlatform(array('ios', 'android'))
                ->addAlias(strval($alias))
                ->setNotificationAlert($content)
                ->options(['apns_production' => true]);
            $response = $jpush->send();
            if (gettype($response) === 'array') {
                if ($response['http_code'] !== 200) {
                    logger($response);
                    return ['status' => 2, 'message' => '发送消息失败'];
                }
            } else if ($response->getHttpCode() !== 200) {
                logger($response);
                return ['status' => 1, 'message' => '禁言成功，但无法发送推送'];
            }
            return ['status' => 1, 'message' => '成功'];
        } catch (Exception $exception) {
            logger($exception);
            return ['status' => 2, 'message' => '发送消息失败'];
        }
//        catch (Exception $exception) {
//            logger(Exception);
//            return ['status' => 2, 'message' => '发送消息失败'];
//        }
    }


    /**
     * 添加系统消息数量
     * @param $user_id
     * @return bool|int
     */
    static function PushNum($user_id)
    {
        if (DB::table('jpush_num')->where('user_id', $user_id)->exists()) {
            return DB::table('jpush_num')->where('user_id', $user_id)->increment('system_num');
        } else {
            return DB::table('jpush_num')->insert([
                'user_id' => $user_id,
                'fabulous_num' => 0,
                'comment_num' => 0,
                'system_num' => 1,
                'sum_num' => 0,
            ]);
        }

    }


    /**
     * 给某个人推送
     * @param $user_id
     * @param $content
     * @return array|Exception
     * @throws Exception
     */
    static function PushOneMessage($user_id, $content)
    {
        //添加系统消息
        DB::beginTransaction();

        if (!DB::table('jpush')->insert(
            [
                'title' => '系统消息',
                'content' => $content,
                'ctime' => date('Y-m-d H:i:s', time()),
                'user_id' => $user_id
            ]
        )) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }
        if (!Curl::PushNum($user_id)) {
            DB::rollBack();

            return ['status' => 2, 'message' => '发送系统消息失败'];
        }
        //推送
//        $a = Curl::GetCurl(Curl::CURL_URI . Curl::CURL_ORDERPUSH, ['alias' => $user_id, 'content' => $content, 'pcs' => 3]);
//        dd($a);
        $jpush = self::PushOne($user_id, $content);
        if ($jpush['status'] !== 1) {
            DB::rollBack();

            return $jpush;
        }
        DB::commit();

        return $jpush;
    }


    /**
     * 给所有人推送消息
     * @param $content
     * @return array
     * @throws Exception
     */
    static function PushMessage($content)
    {
        //添加系统消息
        DB::beginTransaction();

        if (!DB::table('jpush')->insert(
            [
                'title' => '系统消息',
                'content' => $content,
                'ctime' => date('Y-m-d H:i:s', time()),
            ]
        )) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }
        $pushNumALL = Curl::PushNumALL();
        if ($pushNumALL['status'] !== 1) {
            DB::rollBack();

            return $pushNumALL;
        }
        $jpush = self::PushAll($content);
        if ($jpush['status'] !== 1) {
            DB::rollBack();

            return $jpush;
        }
        DB::commit();

        return $jpush;
    }

    /**
     * 极光推送所有人
     * @param $content
     * @return array
     */
    static function PushAll($content)
    {
        try {
            $jpush = new Jpush(env('JPUSH_KEY'), env('JPUSH_SECRET'));
            $jpush = $jpush->push()
                ->setPlatform(array('ios', 'android'))
                ->addAllAudience()
                ->setNotificationAlert($content)
                ->options(['apns_production' => true]);
            $response = $jpush->send();
            if (gettype($response) === 'array') {
                if ($response['http_code'] !== 200) {
                    logger($response);
                    return ['status' => 2, 'message' => '发送消息失败'];
                }
            } else if ($response->getHttpCode() !== 200) {
                logger($response);
                return ['status' => 1, 'message' => '禁言成功，但无法发送推送'];
            }
            return ['status' => 1, 'message' => '成功'];
        } catch (Exception $exception) {
            logger($exception);
            return ['status' => 2, 'message' => '发送消息失败'];
        }
    }


    /**
     * 推送给所有人添加pushnum
     * @return array
     * @throws Exception
     */
    static function PushNumALL()
    {
        DB::beginTransaction();

        if (!DB::table('jpush_num')->increment('system_num')) {
            DB::rollBack();

            return ['status' => 2,'message' => '添加消息数量失败'];
        }
        //找出pushnum里没有的user_id
        $user_ids_old = DB::table('jpush_num')->pluck('user_id')->toArray();
        $user_ids =User::whereNotIn('c_id',$user_ids_old)->where('sign', User::SIGN_YES)->pluck('c_id')->toArray();
        //添加
        $insert = [];
        if (count($user_ids)) {
            foreach ($user_ids as $user_id) {
                $insert[] = [
                    'user_id' => $user_id,
                    'system_num' => 1
                ];
            }
            if (!DB::table('jpush_num')->insert($insert)) {
                DB::rollBack();

                return ['status' => 2,'message' => '添加消息数量失败'];
            }
        }
        DB::commit();

        return ['status' => 1, 'message' => '成功'];

    }


}
